package run.iget.admin.system.service.impl;

import java.util.ArrayList;
import java.util.List;

import org.springframework.stereotype.Service;

import com.mybatisflex.core.query.QueryWrapper;
import com.mybatisflex.spring.service.impl.ServiceImpl;

import cn.hutool.core.collection.CollectionUtil;
import run.iget.admin.system.entity.AdministratorRole;
import run.iget.admin.system.entity.table.AdministratorRoleTableDef;
import run.iget.admin.system.mapper.AdministratorRoleMapper;
import run.iget.admin.system.service.AdministratorRoleService;

/**
 * <p>
 * 管理员-角色关联表 服务实现类
 * </p>
 *
 * @author 大周
 * @since 2022-02-07
 */
@Service
public class AdministratorRoleServiceImpl extends ServiceImpl<AdministratorRoleMapper, AdministratorRole>
        implements AdministratorRoleService {

    @Override
    public List<Long> getRoleIdsByUserId(Long adminId) {
        QueryWrapper queryWrapper = QueryWrapper.create().select(AdministratorRoleTableDef.ADMINISTRATOR_ROLE.ROLE_ID)
                .where(AdministratorRoleTableDef.ADMINISTRATOR_ROLE.ADMINISTRATOR_ID.eq(adminId));
        return this.mapper.selectListByQueryAs(queryWrapper, Long.class);
    }

    @Override
    public List<Long> getUserIdsByRoleId(Long roleId) {
        QueryWrapper queryWrapper = QueryWrapper.create()
                .select(AdministratorRoleTableDef.ADMINISTRATOR_ROLE.ADMINISTRATOR_ID)
                .where(AdministratorRoleTableDef.ADMINISTRATOR_ROLE.ROLE_ID.eq(roleId));
        return this.mapper.selectListByQueryAs(queryWrapper, Long.class);
    }

    @Override
    public void relationRole(Long administratorId, List<Long> roleIds) {
        // 删除之前管理的角色
        QueryWrapper queryWrapper = QueryWrapper.create()
                .where(AdministratorRoleTableDef.ADMINISTRATOR_ROLE.ADMINISTRATOR_ID.eq(administratorId));
        this.remove(queryWrapper);
        if (CollectionUtil.isNotEmpty(roleIds)) {
            List<AdministratorRole> administratorRoleList = new ArrayList<>(roleIds.size());
            AdministratorRole administratorRole = null;
            for (Long roleId : roleIds) {
                administratorRole = new AdministratorRole();
                administratorRole.setAdministratorId(administratorId);
                administratorRole.setRoleId(roleId);
                administratorRoleList.add(administratorRole);
            }
            this.saveBatch(administratorRoleList);
        }
    }
}
